<!DOCTYPE html>

<html lang="en">

<head>

  <meta charset="UTF-8">

  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <title>像素RPG</title>

  <style>

    body {

      margin: 0;

      display: flex;

      justify-content: center;

      align-items: center;

      height: 100vh;

      background-color: #333;

    }

    canvas {

      border: 1px solid #fff;

      background-color: #000;

    }

  </style>

</head>

<body>

  <canvas id="gameCanvas" width="320" height="320"></canvas>

  <script>

    const canvas = document.getElementById('gameCanvas');

    const ctx = canvas.getContext('2d');



    // 游戏配置

    const tileSize = 32; // 每个格子的大小

    const map = [ // 地图数据，0是草地，1是墙

      [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],

      [0, 1, 1, 1, 0, 0, 1, 1, 1, 0],

      [0, 0, 0, 1, 0, 0, 1, 0, 0, 0],

      [0, 1, 0, 1, 0, 0, 1, 0, 1, 0],

      [0, 1, 0, 0, 0, 0, 0, 0, 1, 0],

      [0, 1, 1, 1, 1, 1, 1, 1, 1, 0],

      [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],

    ];

    const player = { x: 1, y: 1 }; // 玩家初始位置



    // 绘制地图

    function drawMap() {

      for (let y = 0; y < map.length; y++) {

        for (let x = 0; x < map[y].length; x++) {

          if (map[y][x] === 0) {

            ctx.fillStyle = 'green'; // 草地

          } else if (map[y][x] === 1) {

            ctx.fillStyle = 'gray'; // 墙壁

          }

          ctx.fillRect(x * tileSize, y * tileSize, tileSize, tileSize);

        }

      }

    }



    // 绘制玩家

    function drawPlayer() {

      ctx.fillStyle = 'red';

      ctx.fillRect(player.x * tileSize, player.y * tileSize, tileSize, tileSize);

    }



    // 碰撞检测

    function canMove(x, y) {

      if (x < 0 || y < 0 || x >= map[0].length || y >= map.length || map[y][x] === 1) {

        return false;

      }

      return true;

    }



    // 监听键盘事件

    document.addEventListener('keydown', (e) => {

      let newX = player.x;

      let newY = player.y;



      if (e.key === 'ArrowUp') newY--; // 上

      if (e.key === 'ArrowDown') newY++; // 下

      if (e.key === 'ArrowLeft') newX--; // 左

      if (e.key === 'ArrowRight') newX++; // 右



      if (canMove(newX, newY)) {

        player.x = newX;

        player.y = newY;

      }



      render();

    });



    // 渲染游戏

    function render() {

      ctx.clearRect(0, 0, canvas.width, canvas.height);

      drawMap();

      drawPlayer();

    }



    render();

  </script>

</body>

</html>